// pages/customer/customer.js
import http from '../../utils/http.js';
const apiConfig = require('../../utils/apiConfig.js');

Page({
  data: {
    users: [],
    loading: false,
    showFilterPopup: false,
    customer_name: '',
    counties: [],
    towns: [],
    villages: [],
    selectedCounty: null,
    selectedTown: null,
    selectedVillage: null,
    selectedCountyIndex: -1,
    selectedTownIndex: -1,
    selectedVillageIndex: -1,
    page: 1,
    perPage: 10,
    total: 0
  },

  onLoad() {
    console.log('页面加载，开始加载县数据和用户数据');
    this.loadCounties();
    this.loadUsers();
  },

  // 加载县数据
  loadCounties() {
    http.request({
      url: '/api/getCounties',
      method: 'GET'
    }).then(res => {
      if (res.status === 200) {
        this.setData({
          counties: res.data.map(item => ({
            id: item.id,
            address_name: item.address_name
          }))
        }, () => {
          console.log('县数据加载完成:', this.data.counties);
        });
      }
    }).catch(err => {
      console.error('县数据加载失败:', err);
    });
  },

  // 加载镇数据
  loadTowns(provinceId) {
    http.request({
      url: '/api/getCities',
      method: 'GET',
      data: { provinceId: provinceId }
    }).then(res => {
      if (res.status === 200) {
        this.setData({
          towns: res.data,
          villages: [],
          selectedTown: null,
          selectedVillage: null
        }, () => {
          console.log(`县 ID ${provinceId} 的镇数据加载完成:`, this.data.towns);
        });
      }
    }).catch(err => {
      console.error('镇数据加载失败:', err);
    });
  },

  // 加载村数据
  loadVillages(cityId) {
    http.request({
      url: '/api/getDistricts',
      method: 'GET',
      data: { cityId: cityId }
    }).then(res => {
      if (res.status === 200) {
        this.setData({
          villages: res.data,
          selectedVillage: null
        }, () => {
          console.log(`镇 ID ${cityId} 的村数据加载完成:`, this.data.villages);
        });
      }
    }).catch(err => {
      console.error('村数据加载失败:', err);
    });
  },

  // 加载用户数据
  loadUsers() {
    if (this.data.loading) return;
    console.log('开始加载用户数据，筛选条件:', {
      county: this.data.selectedCounty?.id ?? '',
      town: this.data.selectedTown?.id ?? '',
      village: this.data.selectedVillage?.id ?? '',
      customer_name: this.data.customer_name
    });
    this.setData({ loading: true });

    http.request({
      url: apiConfig.getCustomerList,
      method: 'GET',
      data: {
        page: this.data.page,
        per_page: this.data.perPage,
        customer_name: this.data.customer_name,
        county: this.data.selectedCounty?.id ?? '',
        town: this.data.selectedTown?.id ?? '',
        village: this.data.selectedVillage?.id ?? ''
      }
    }).then(res => {
      console.log('用户数据请求成功:', res);
      this.setData({
        users: this.data.page === 1 ? res.data.data : this.data.users.concat(res.data.data),
        total: res.data.total,
        loading: false
      });
    }).catch(err => {
      console.error('请求失败:', err);
      wx.showToast({
        title: err.message || '加载失败',
        icon: 'none'
      });
      this.setData({ loading: false });
    });
  },

  // 显示筛选弹窗
  showFilter() {
    console.log('显示筛选弹窗');
    this.setData({ showFilterPopup: true });
  },

  // 隐藏筛选弹窗
  hideFilter() {
    console.log('隐藏筛选弹窗');
    this.setData({ showFilterPopup: false });
  },

  // 县选择改变
  bindCountyChange(e) {
    const index = e.detail.value;
    const selectedCounty = this.data.counties[index];
    console.log('县选择改变，选中县:', selectedCounty.address_name);
    this.setData({ selectedCounty, selectedCountyIndex: index }, () => {
      this.loadTowns(selectedCounty.id);
    });
  },

  // 镇选择改变
  bindTownChange(e) {
    const index = e.detail.value;
    const selectedTown = this.data.towns[index];
    console.log('镇选择改变，选中镇:', selectedTown.address_name);
    this.setData({ selectedTown, selectedTownIndex: index }, () => {
      this.loadVillages(selectedTown.id);
    });
  },

  // 村选择改变
  bindVillageChange(e) {
    const index = e.detail.value;
    const selectedVillage = this.data.villages[index];
    console.log('村选择改变，选中村:', selectedVillage.address_name);
    this.setData({ selectedVillage, selectedVillageIndex: index });
  },

  // 确认筛选
  confirmFilter() {
    console.log('确认筛选，当前筛选条件:', {
      selectedCounty: this.data.selectedCounty,
      selectedTown: this.data.selectedTown,
      selectedVillage: this.data.selectedVillage,
    });
    this.setData({ page: 1}, () => {
      this.loadUsers();
      this.hideFilter();
    });
  },

  // 下拉刷新
  onPullDownRefresh() {
    console.log('触发下拉刷新');
    this.setData({ page: 1 }, () => {
      this.loadUsers();
      wx.stopPullDownRefresh();
    });
  },

  // 上拉加载更多
  loadMore() {
    if (this.data.users.length >= this.data.total) return;
    console.log('触发上拉加载更多');
    this.setData({ page: this.data.page + 1 }, () => {
      this.loadUsers();
    });
  },

  handleAddCustomer() {
    wx.navigateTo({
      url: '/pages/customer-add/customer-add'
    });
  },

  handleViewDetail(e) {
    const id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/customer-edit/customer-edit?id=${id}`
    });
  },

  handleSearchInput(e) {
    this.setData({ customer_name: e.detail.value });
  }
});